import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Input,
  Button,
  Modal,
  Divider,
  Icon,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};
const CreateForm = Form.create()(props => {
  const { modalVisible, form, addDataFn, updateFn, handleModalVisible, text} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(text) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑业务':'新增业务'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formLayout} label="业务名称">
        {form.getFieldDecorator('bmname', {
          rules: [{required: true,message:'业务名称不能为空',}, {max: 60, message: "字符长度不能超过60"}],
          initialValue: text&&text.bmname || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem {...formLayout} label="业务编码">
        {form.getFieldDecorator('bmcode', {
          rules: [{required: true,message:'业务编码不能为空'},{max: 60, message: "字符长度不能超过60"}],
          initialValue: text&&text.bmcode || ''
        })(
          <Input placeholder="请输入"/>
        )}
      </FormItem>

    </Modal>
  );
});

@Form.create()
@connect(({ bnsMag, loading }) => ({
  bnsMag,
  loading: loading.models.bnsMag,
}))
@Form.create()
class bnsMag extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    text: {},
  };

  columns = [
    {
      title: '业务名称',
      dataIndex: 'bmname',
      width: "40%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },

    {
      title: '业务编码',
      dataIndex: 'bmcode',
      width: "40%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },

    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true,text)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.deleteData(text.id)}>删除</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.pageList();
  }

  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'bnsMag/queryList',
      payload: values,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };
  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  handleThisRowDelete = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bnsMag/remove',
      payload: {id},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text
    });
  };

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const params = {
      id: text.id,
      bmname: fields.bmname,
      bmcode: fields.bmcode,
    }
    dispatch({
      type: 'bnsMag/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const params = {
        bmname: fields.bmname,
        bmcode: fields.bmcode,
    }
    dispatch({
      type: 'bnsMag/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  render() {
    const {
      bnsMag: { data },
      loading,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      editFormValues,
      text
    } = this.state;

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };
    return (
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
        <div className={styles.tableList}>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.id}
          />
        </div>
      </Card>

    );
  }
}

export default bnsMag;
